import React, { useEffect, useState } from 'react'
import { InfiniteScroll, List, DotLoading } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import TopNavbar from '../../components/TopNavbar'
import styles from './index.module.css'
import { fetchRecords, getLocalRecords } from '../../services/recordsService'

const Records = () => {
  const navigate = useNavigate()
  const [page, setPage] = useState(1)
  const [data, setData] = useState([])
  const [hasMore, setHasMore] = useState(true)

  useEffect(() => {
    // 先加载本地记录（最新）
    const local = getLocalRecords()
    if (local && local.length) {
      setData(local)
    }
    loadMore()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const loadMore = async () => {
    const res = await fetchRecords({ page })
    setData(prev => [...prev, ...res.items])
    setPage(prev => prev + 1)
    setHasMore(res.hasMore)
  }

  return (
    <div className={styles.page}>
      <TopNavbar title="就诊记录" showBack onBack={() => navigate(-1)} />
      <div className={styles.container}>
        <List>
          {data.map(item => (
            <List.Item key={item.id} description={<>
              <div>就诊医院 {item.hospital}</div>
              <div>挂号科室 {item.dept}</div>
              <div>挂号医生 {item.doctor}</div>
            </>}>
              就诊时间：{item.date}
            </List.Item>
          ))}
        </List>
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
          {hasMore && <span className={styles.loading}><DotLoading /></span>}
        </InfiniteScroll>
      </div>
    </div>
  )
}

export default Records


